/*
 *  Copyright 2012 Dirk Vranckaert
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package eu.vranckaert.vvl.service.impl;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import eu.vranckaert.vvl.exception.webservice.WebServiceException;
import eu.vranckaert.vvl.exception.webservice.WebServiceRequestFailureException;
import eu.vranckaert.vvl.service.WebService;
import eu.vranckaert.vvl.utils.context.Logger;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

/**
 * User: DIRK VRANCKAERT
 * Date: 17/02/12
 * Time: 11:23
 */
public class WebServiceImpl implements WebService {
    private static final String LOG_TAG = WebServiceImpl.class.getSimpleName();

    protected Context ctx;
    private HttpClient client;

    public WebServiceImpl(Context ctx) {
        this.ctx = ctx;
    }

    private HttpClient getHttpClient() {
        client = new DefaultHttpClient();
        return client;
    }

    @Override
    public String doHtmlGet(String url) throws WebServiceException, WebServiceRequestFailureException {
        if (Logger.isLogEnabled())
            Log.d(LOG_TAG, "Incoming URL for HTML: " + url);

        HttpClient httpClient = getHttpClient();
        HttpGet get = new HttpGet(url);

        String result = "";
        int status = 200;

        try {
            HttpResponse response = httpClient.execute(get);
            status = response.getStatusLine().getStatusCode();
            result = EntityUtils.toString(response.getEntity());
        } catch (UnknownHostException e) {
            String message = "Could not connect to host.";
            Log.e(LOG_TAG, message, e);
            throw new WebServiceException(message, e);
        } catch (IOException e) {
            String message = "IOException for URL " + url;
            Log.w(LOG_TAG, message, e);
            throw new WebServiceException(message, e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

        if (status != 200) {
            String message = "Web request failed with status code " + status + " for URL " + url;
            Log.w(LOG_TAG, message);
            throw new WebServiceRequestFailureException(message, status);
        } else {
            if (Logger.isLogEnabled())
                Log.i(LOG_TAG, "Web request successfully for URL " + url);
        }

        return result;
    }

    @Override
    public Bitmap doImageGet(String url) throws WebServiceException {
        if (Logger.isLogEnabled())
            Log.d(LOG_TAG, "Incoming URL for image: " + url);
        Bitmap image = null;
        try {
            InputStream in = new URL(url).openStream();
            image = BitmapFactory.decodeStream(in);
        } catch (MalformedURLException e) {
            String message = "The URL seems to be malformed for " + url;
            Log.e(LOG_TAG, message, e);
            throw new WebServiceException(message, e);
        } catch (IOException e) {
            String message = "IOException for URL " + url;
            Log.e(LOG_TAG, message, e);
            throw new WebServiceException(message, e);
        }
        return image;
    }
}
